<template>
  <div class="app-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="left-buttons">
        <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
      </div>
      <div class="right-buttons">
        <el-button
          v-if="type !== 'view'"
          type="success"
          icon="el-icon-plus"
          @click="addItem"
          >新增</el-button
        >
        <el-button
          v-if="type !== 'view'"
          type="primary"
          icon="el-icon-check"
          @click="saveData"
          >保存</el-button
        >
        <el-button type="" icon="el-icon-menu" @click="goToList"
          >列表</el-button
        >
        <el-button
          v-if="type !== 'view'"
          type="danger"
          icon="el-icon-delete"
          @click="deleteSelected"
          >批量删除</el-button
        >

        <el-button type="info" icon="el-icon-printer" @click="printForm"
          >打印</el-button
        >
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <h2>人事档案管理手册</h2>
      </div>
      <el-table
        :data="list"
        border
        class="custom-table"
        size="small"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          class="selection"
          v-if="type !== 'view'"
          type="selection"
          width="55"
        />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="事业部">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.businessUnit"
              placeholder="请输入事业部"
              :disabled="type === 'view'"
            />
          </template>
        </el-table-column>
        <el-table-column label="部门">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.department"
              placeholder="请输入部门"
              :disabled="type === 'view'"
            />
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="120">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.employeeName"
              placeholder="请输入姓名"
              :disabled="type === 'view'"
            />
          </template>
        </el-table-column>
        <el-table-column label="性别" width="100">
          <template slot-scope="{ row }">
            <el-select
              v-model="row.gender"
              placeholder="请选择"
              :disabled="type === 'view'"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="工号" width="120">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.employeeNumber"
              placeholder="请输入工号"
              :disabled="type === 'view'"
            />
          </template>
        </el-table-column>
        <el-table-column label="入职日期" width="160">
          <template slot-scope="{ row }">
            <el-date-picker
              v-model="row.entryDate"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              :disabled="type === 'view'"
            />
          </template>
        </el-table-column>
        <el-table-column label="籍贯">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.nativePlace"
              placeholder="请输入籍贯"
              :disabled="type === 'view'"
            />
          </template>
        </el-table-column>
        <el-table-column label="档案编号" width="120">
          <template slot-scope="{ row }">
            <el-input
              v-model="row.archiveNumber"
              placeholder="请输入档案编号"
              :disabled="type === 'view'"
            />
          </template>
        </el-table-column>
      </el-table>

    <!-- 底部说明 -->
    <div class="footer-info">
      <span>表单编号及版本：AM-JY-287 A0 </span><span>保存期限：长期</span>
    </div>
    </div>
  </div>
</template>

<script>
import {
  saveOrUpdateBatchPersonnelArchive,
  getPersonnelArchiveById,
} from "@/api/personnelArchive";

export default {
  data() {
    return {
      type: "create", // create, edit, view
      id: undefined,
      list: [
        {
          businessUnit: "",
          department: "",
          employeeName: "",
          gender: "",
          employeeNumber: "",
          entryDate: "",
          nativePlace: "",
          archiveNumber: "",
        },
      ],
      selectedItems: [],
    };
  },
  created() {
    // 从路由参数获取操作类型和ID
    const { type, id } = this.$route.query;
    this.type = type || "create";
    this.id = id;

    // 如果是编辑或查看，则获取数据
    if (this.id) {
      this.fetchData();
    }
  },
  methods: {
    fetchData() {
      getPersonnelArchiveById(this.id).then((response) => {
        // 保留原始ID
        const data = response.data.data;
        this.list = [
          {
            id: data.id,
            businessUnit: data.businessUnit,
            department: data.department,
            employeeName: data.employeeName,
            gender: data.gender,
            employeeNumber: data.employeeNumber,
            entryDate: data.entryDate,
            nativePlace: data.nativePlace,
            archiveNumber: data.archiveNumber,
          },
        ];
      });
    },
    handleSelectionChange(val) {
      this.selectedItems = val;
    },
    saveData() {
      // 验证必填字段
      const requiredFields = [
        "employeeName",
        "employeeNumber",
        "gender",
        "entryDate",
      ];
      const invalidItems = this.list.filter((item) => {
        return requiredFields.some((field) => !item[field]);
      });

      if (invalidItems.length > 0) {
        this.$message({
          type: "warning",
          message: "请填写完整信息（姓名、工号、性别、入职日期为必填项）",
        });
        return;
      }

      const archives = this.list.map((item) => ({
        ...(item.id ? { id: item.id } : {}), // 如果数据有ID则使用该ID
        businessUnit: item.businessUnit,
        department: item.department,
        employeeName: item.employeeName,
        gender: item.gender,
        employeeNumber: item.employeeNumber,
        entryDate: item.entryDate,
        nativePlace: item.nativePlace,
        archiveNumber: item.archiveNumber,
      }));

      saveOrUpdateBatchPersonnelArchive(archives)
        .then(() => {
          this.$message({
            type: "success",
            message: this.type === "create" ? "创建成功" : "更新成功",
          });
          this.goToList();
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: "保存失败：" + error.message,
          });
        });
    },
    addItem() {
      this.list.push({
        id: undefined, // 新增的数据没有ID
        businessUnit: "",
        department: "",
        employeeName: "",
        gender: "",
        employeeNumber: "",
        entryDate: "",
        nativePlace: "",
        archiveNumber: "",
      });
    },
    deleteSelected() {
      if (this.selectedItems.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择要删除的记录",
        });
        return;
      }

      this.$confirm("确认删除选中的记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.list = this.list.filter(
            (item) => !this.selectedItems.includes(item)
          );
          this.selectedItems = [];
          this.$message({
            type: "success",
            message: "删除成功",
          });
        })
        .catch(() => {});
    },
    goToList() {
      this.$router.push("/main/renshi/renshizhidu/rsdangangl/rsdanganglList");
    },
    goBack() {
      this.$router.push("/main/renshi/renshizhidu");
    },
    printForm() {
      // 创建一个样式元素
      const style = document.createElement("style");
      style.type = "text/css";
      style.media = "print";
      style.textContent = "@page { size: A4 landscape; }";
      // 将样式添加到文档头部
      document.head.appendChild(style);
      // 执行打印
      window.print();
      // 打印完成后移除样式
      document.head.removeChild(style);
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  /* background-color: #f5f7fa; */
  height: calc(100vh - 40px);
  width: 1200px;
  margin: 0 auto;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  align-items: center;
}

.left-buttons {
  display: flex;
  align-items: center;
}

.right-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.table-header {
  margin-bottom: 20px;
  text-align: center;
}

.table-header h2 {
  color: #303133;
  margin: 0;
}

.custom-table {
  width: 100%;
  margin-bottom: 20px;
}

.custom-table ::v-deep .el-table__header-wrapper th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  font-size: 1em;
}

.custom-table ::v-deep .el-input__inner {
  height: 32px;
  line-height: 32px;
}

.custom-table ::v-deep .el-select {
  width: 100%;
}

.footer-info {
  margin-top: 20px;
  text-align: center;
  color: #909399;
  font-size: 0.9em;
  display: flex;
  justify-content: space-between;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .toolbar {
    flex-direction: column;
    gap: 10px;
  }

  .left-buttons,
  .right-buttons {
    width: 100%;
  }

  .right-buttons {
    justify-content: flex-start;
  }
}
@media print {
  .table-container {
    box-shadow: none !important;
    /* border: none !important; */
  }
  .toolbar {
    display: none !important;
  }
  /* .custom-table ::v-deep .el-checkbox__inner {
    display: none !important;
  } */
  /* ::v-deep
    th.el-table_1_column_1.el-table-column--selection.is-leaf.el-table__cell {
    display: none !important;
  }
  ::v-deep td.el-table_2_column_11.el-table-column--selection.el-table__cell {
    display: none !important;
  } */
  ::v-deep input.el-input__inner {
    border: none !important;
  }
  ::v-deep textarea.el-textarea__inner {
    border: none !important;
    resize: none;
  }
  ::v-deep i.el-input__icon {
    display: none !important;
  }
}
</style>